package com.mipo.company.flytek.openapi;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 接口文档地址为：
 * 中心文档 http://dev.open.changyan.com/docenter/login
 * 区域文档 http://open.ewp.changyan.cn/docenter/api_list
 * 用户名和密码：reader/123456
 * 
 * 中心url：xxx
 * 区域url：http://open.edc.linyi.net.cn/api；临沂和北仑都调用的是区域的openapi
 * 
 *
 * @author jack lee
 **/

public class LinyiOpenApiTest {
	public static String HEAD_DESKTOP     = "http://open.edc.linyi.net.cn/api?format=json&appkey=ca91dd6f8d3a4bdcb41fdb576093e8f2&version=1.0&access_token=6f36eb9a-7fed-48aa-aaa7-ba12c7c52d8a&";
	public static void main(String[] args) throws Exception {
		//getOauthToken(); // 获取tokent
		coreUserGet(); // 获取用户信息
		//coreUcUpdatePasswordByUniqueInfo(); // 通过用户的唯一属性更新用户密码
		
		
	}
	
	public static void coreUcUpdatePasswordByUniqueInfo() throws Exception {
		String url = HEAD_DESKTOP + "method=core.uc.update.password.by.unique.info&key=loginName&value=swwang&oldPassword=4f33945760e25d74e805f0e93bf9d3f0&newPassword=4f33945760e25d74e805f0e93bf9d3f0";
		excuteGetRequest(url);
	}
	
	
	public static void coreUserGet() throws Exception {
		String url = HEAD_DESKTOP + "method=core.user.get&key=loginName&value=lijie_test";
		excuteGetRequest(url);
	}
	
	public static void getOauthToken() throws Exception {
		// 这个是desk-top的app key
		String url = "http://open.edc.linyi.net.cn/authorization-token-server/oauth/token?client_id=ca91dd6f8d3a4bdcb41fdb576093e8f2&client_secret=1f2a43c782a32397dc19c78c4364c48f&grant_type=client_credentials";
		excuteGetRequest(url); // 返回desk-top的token为：c7cfe3ee-e259-4f99-883f-50f17a5dec7f；
	}
	
	public static void excuteGetRequest(String url) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpClient.execute(httpGet); // 4.3版本不设置超时的话，一旦服务器没有响应，等待时间N久(>24小时)。
		HttpEntity entity = response.getEntity(); // 返回报文实体
		StatusLine status = response.getStatusLine();
		System.out.println("返回的状态码为：" + status); // 具体返回码(200)为status.getStatusCode(); 
		String ret = EntityUtils.toString(entity); // 将返回报文实体转换为字符串
		System.out.println("返回的报文为：" + ret);
		EntityUtils.consume(entity);  // 释放是否可以去掉？
		response.close(); // 关闭资源,可以写在finally里
		httpGet.releaseConnection(); // 释放资源
		httpClient.close(); // 关闭资源
	}
	
	
	
	
}
